package bearworker.zxl.config;

import bearworker.zxl.utils.PriviUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * Created by 逍遥的熊 on 2017/11/16.
 */

@Configuration
@PropertySource(value = { "classpath:${pro.env}/redis.properties" })
public class RedisConfig {

    @Resource
    private Environment environment;

    @Bean(name = "poolConfig")
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(environment.getRequiredProperty("redis.maxIdle",Integer.class));
        poolConfig.setTestOnBorrow(environment.getRequiredProperty("redis.testOnBorrow",Boolean.class));
        return poolConfig;
    }

    @Bean(name = "jedisConnectionFactory")
    public JedisConnectionFactory jedisConnectionFactory(){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(this.jedisPoolConfig());
        jedisConnectionFactory.setHostName(environment.getRequiredProperty("redis.host"));
        jedisConnectionFactory.setPort(environment.getRequiredProperty("redis.port",Integer.class));

        if(StringUtils.isNotEmpty(environment.getRequiredProperty("redis.pass"))) {
            jedisConnectionFactory.setPassword(environment.getRequiredProperty("redis.pass"));
        }
        if(StringUtils.isNotEmpty(environment.getRequiredProperty("redis.db"))) {
            jedisConnectionFactory.setDatabase(environment.getRequiredProperty("redis.db", Integer.class));
        }
        jedisConnectionFactory.setUsePool(true);
        return jedisConnectionFactory;
    }

    @Bean(name = "redisTemplate")
    public StringRedisTemplate redisTemplate(){
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(this.jedisConnectionFactory());
        return redisTemplate;
    }
}
